'use client';

import { useState } from 'react';
import Layout from '../components/Layout';
import { IconSearch, IconLoader2 } from '@tabler/icons-react';

interface NutritionInfo {
  name: string;
  category: string;
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
  fiber: number;
  vitamins: { [key: string]: number };
  minerals: { [key: string]: number };
  servingSize: string;
  description?: string;
}

export default function NutritionSearch() {
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<NutritionInfo[]>([]);
  const [selectedFood, setSelectedFood] = useState<NutritionInfo | null>(null);

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchTerm.trim()) return;

    setLoading(true);
    try {
      const res = await fetch(`/api/nutrition/search?q=${encodeURIComponent(searchTerm)}`, {
        credentials: 'include',
      });

      if (!res.ok) {
        throw new Error('搜索失败');
      }

      const data = await res.json();
      setResults(data.results);
    } catch (error) {
      console.error('搜索错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout>
      <div className="max-w-6xl mx-auto px-4 py-8">
        <h1 className="text-2xl font-bold mb-8">营养信息查询</h1>

        {/* 搜索表单 */}
        <form onSubmit={handleSearch} className="mb-8">
          <div className="flex gap-4">
            <div className="flex-1 relative">
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="输入食物名称搜索..."
                className="input-field w-full pl-12"
              />
              <IconSearch className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            </div>
            <button type="submit" className="btn-primary min-w-[120px]" disabled={loading}>
              {loading ? (
                <IconLoader2 className="w-5 h-5 animate-spin mx-auto" />
              ) : (
                '搜索'
              )}
            </button>
          </div>
        </form>

        {/* 搜索结果和详细信息 */}
        <div className="grid md:grid-cols-3 gap-6">
          {/* 搜索结果列表 */}
          <div className="md:col-span-1">
            <div className="bg-white rounded-lg shadow-sm p-4">
              <h2 className="text-lg font-semibold mb-4">搜索结果</h2>
              {results.length > 0 ? (
                <div className="space-y-2">
                  {results.map((food, index) => (
                    <button
                      key={index}
                      onClick={() => setSelectedFood(food)}
                      className={`w-full text-left p-3 rounded-lg transition-colors ${
                        selectedFood === food
                          ? 'bg-blue-50 text-blue-700'
                          : 'hover:bg-gray-50'
                      }`}
                    >
                      <div className="font-medium">{food.name}</div>
                      <div className="text-sm text-gray-500">{food.servingSize}</div>
                    </button>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  {loading ? '搜索中...' : '暂无搜索结果'}
                </div>
              )}
            </div>
          </div>

          {/* 详细营养信息 */}
          <div className="md:col-span-2">
            {selectedFood ? (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold mb-2">{selectedFood.name}</h2>
                <div className="text-gray-600 mb-6">
                  {selectedFood.description || `每份${selectedFood.servingSize}`}
                </div>

                {/* 主要营养素 */}
                <div className="grid md:grid-cols-4 gap-4 mb-8">
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <div className="text-sm text-gray-600">热量</div>
                    <div className="text-xl font-bold text-blue-600">
                      {selectedFood.calories} 千卡
                    </div>
                  </div>
                  <div className="bg-green-50 p-4 rounded-lg">
                    <div className="text-sm text-gray-600">蛋白质</div>
                    <div className="text-xl font-bold text-green-600">
                      {selectedFood.protein}g
                    </div>
                  </div>
                  <div className="bg-yellow-50 p-4 rounded-lg">
                    <div className="text-sm text-gray-600">碳水化合物</div>
                    <div className="text-xl font-bold text-yellow-600">
                      {selectedFood.carbs}g
                    </div>
                  </div>
                  <div className="bg-red-50 p-4 rounded-lg">
                    <div className="text-sm text-gray-600">脂肪</div>
                    <div className="text-xl font-bold text-red-600">
                      {selectedFood.fat}g
                    </div>
                  </div>
                </div>

                {/* 维生素和矿物质 */}
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <h3 className="font-semibold mb-3">维生素含量</h3>
                    <div className="space-y-2">
                      {Object.entries(selectedFood.vitamins).map(([name, value]) => (
                        <div key={name} className="flex justify-between">
                          <span className="text-gray-600">{name}</span>
                          <span className="font-medium">{value}mg</span>
                        </div>
                      ))}
                    </div>
                  </div>
                  <div>
                    <h3 className="font-semibold mb-3">矿物质含量</h3>
                    <div className="space-y-2">
                      {Object.entries(selectedFood.minerals).map(([name, value]) => (
                        <div key={name} className="flex justify-between">
                          <span className="text-gray-600">{name}</span>
                          <span className="font-medium">{value}mg</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="bg-white rounded-lg shadow-sm p-8 text-center text-gray-500">
                请从左侧选择食物查看详细营养信息
              </div>
            )}
          </div>
        </div>
      </div>
    </Layout>
  );
} 